package com.bwda.dsrs.filecenter.controller;

import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.AesEncryptPaddingUtil;
import com.bwda.dsrs.base.util.CopyUtil;
import com.bwda.dsrs.filecenter.domain.BusinessConstants;
import com.bwda.dsrs.filecenter.domain.condition.dbgroup.DbGroupCondition;
import com.bwda.dsrs.filecenter.domain.condition.dbgrouprel.DbGroupRelCondition;
import com.bwda.dsrs.filecenter.domain.condition.dbinfo.DbInfoCondition;
import com.bwda.dsrs.filecenter.domain.exception.BusinessServiceException;
import com.bwda.dsrs.filecenter.domain.form.dbinfo.DbInfoCreateForm;
import com.bwda.dsrs.filecenter.domain.form.dbinfo.DbInfoQueryForm;
import com.bwda.dsrs.filecenter.domain.form.dbinfo.DbInfoUpdateForm;
import com.bwda.dsrs.filecenter.domain.po.dbgroup.DbGroupPo;
import com.bwda.dsrs.filecenter.domain.po.dbgrouprel.DbGroupRelPo;
import com.bwda.dsrs.filecenter.domain.po.dbinfo.DbInfoPo;
import com.bwda.dsrs.filecenter.domain.vo.dbinfo.DbInfoDbNameListVo;
import com.bwda.dsrs.filecenter.domain.vo.dbinfo.DbInfoVo;
import com.bwda.dsrs.filecenter.service.DbGroupRelService;
import com.bwda.dsrs.filecenter.service.DbGroupService;
import com.bwda.dsrs.filecenter.service.DbInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/b/dbinfo")
@Api(value = "/b/dbinfo", tags = "数据库信息表")
public class DbInfoController extends BaseController {

	@Autowired
	private DbInfoService dbInfoService;
	@Autowired
	private DbGroupService dbGroupService;
	@Autowired
	private DbGroupRelService dbGroupRelService;

	@Value("${aes_key}")
	private String aeskey;

	@ApiOperation(value = "查询数据库信息表",notes = "查询数据库信息表",httpMethod = "GET")
	@RequestMapping(value = "/query", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<DbInfoVo> query(@ApiParam(value = "id", required = true)@RequestParam Integer dbId) throws BusinessServiceException {
		DbInfoPo po = dbInfoService.queryWithValid(dbId);
		DbInfoVo vo = CopyUtil.transfer(po, DbInfoVo.class);
		return getSuccessResult(vo);
	}

	@ApiOperation(value = "查询数据库信息表数量",notes = "查询数据库信息表数量",httpMethod = "GET")
	@RequestMapping(value = "/queryCount", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<Integer> queryCount(@ModelAttribute@Valid DbInfoQueryForm form) throws BusinessServiceException {
		DbInfoCondition condition = this.getConditionByQueryForm(form);
		int count = dbInfoService.queryCount(condition);
		return getSuccessResult(count);
	}

	@ApiOperation(value = "查询数据库信息表列表",notes = "查询数据库信息表列表",httpMethod = "GET")
	@RequestMapping(value = "/queryList", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<CentreListResponse<DbInfoVo>> queryList(@ModelAttribute@Valid DbInfoQueryForm form) throws BusinessServiceException {
		DbInfoCondition condition = this.getConditionByQueryForm(form);
		condition.setDelFlag(0);
		List<DbInfoPo> poList = dbInfoService.queryLists(condition);
		List<DbInfoVo> voList = CopyUtil.transfer(poList, DbInfoVo.class);
		return getSuccessResult(getListResponse(voList));
	}
	@ApiOperation(value = "查询鉴权后数据库信息表列表",notes = "查询鉴权后数据库信息表列表",httpMethod = "GET")
	@RequestMapping(value = "/queryAuthList", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<CentreListResponse<DbInfoVo>> queryAuthList(@ModelAttribute@Valid DbInfoQueryForm form) throws BusinessServiceException {
		DbInfoCondition dbInfoCondition = this.getConditionByQueryForm(form);
		dbInfoCondition.setPageSize(Integer.MAX_VALUE);
		dbInfoCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
		List<DbInfoPo> poList ;
		List<DbInfoVo> voList = null ;
		if ("sysadmin".equals(getUserCode())) {
			poList = dbInfoService.queryLists(dbInfoCondition);
			voList = CopyUtil.transfer(poList, DbInfoVo.class);
		}
		else {
			DbGroupCondition dbGroupCondition = new DbGroupCondition();
			dbGroupCondition.setPageSize(Integer.MAX_VALUE);
			dbGroupCondition.setAdminUserCode(getUserCode());
			dbGroupCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
//		dbGroupCondition.setStatus(BusinessConstants.NumberConstant.ZERO);
			List<DbGroupPo> dbGroupPos= dbGroupService.queryList(dbGroupCondition);
			if(!CollectionUtils.isEmpty(dbGroupPos)){
				DbGroupRelCondition dbGroupRelCondition = new DbGroupRelCondition();
				dbGroupRelCondition.setPageSize(Integer.MAX_VALUE);
				dbGroupRelCondition.setGroupIdList(dbGroupPos.stream().map(dbGroupPo -> dbGroupPo.getId()).distinct().collect(Collectors.toList()));
				List<DbGroupRelPo> dbGroupRelPos = dbGroupRelService.queryList(dbGroupRelCondition);
				if(!CollectionUtils.isEmpty(dbGroupRelPos)){
					dbInfoCondition.setDbIdList(dbGroupRelPos.stream().map(dbGroupRelPo -> dbGroupRelPo.getDbId()).distinct().collect(Collectors.toList()));
					poList = dbInfoService.queryLists(dbInfoCondition);
					voList = CopyUtil.transfer(poList, DbInfoVo.class);
				}
			}

		}
		return getSuccessResult(getListResponse(voList));
	}
	@ApiOperation(value = "查询数据库信息表列表(带分页)",notes = "查询数据库信息表列表(带分页)",httpMethod = "GET")
	@RequestMapping(value = "/queryPageList", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<CentreCutPageResponse<DbInfoVo>> queryPageList(@ModelAttribute@Valid DbInfoQueryForm form) throws BusinessServiceException {
		DbInfoCondition condition = this.getConditionByQueryForm(form);
		List<DbInfoVo> voList = new ArrayList<>();
		condition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
		int count = dbInfoService.queryCount(condition);
		if (count > BusinessConstants.NumberConstant.ZERO) {
			List<DbInfoPo> poList = dbInfoService.queryList(condition);
			voList = CopyUtil.transfer(poList, DbInfoVo.class);
		}
		return getSuccessResult(getPageResponse(form, count, voList));
	}

	@ApiOperation(value = "新增数据库信息表",notes = "新增数据库信息表",httpMethod = "POST")
	@RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<DbInfoVo> add(@ModelAttribute@Valid DbInfoCreateForm form) throws Exception {
		DbInfoPo po = CopyUtil.transfer(form, DbInfoPo.class);
		String aesdec =AesEncryptPaddingUtil.decrypt(form.getDbPassword(),aeskey);
		if (StringUtils.isBlank(aesdec)){
			getFailResult("密码加密方式有误");
		}
		po.setDbPassword(AesEncryptPaddingUtil.encrypt(aesdec,aeskey));
		dbInfoService.insert(po);
		DbInfoVo vo = CopyUtil.transfer(po, DbInfoVo.class);
		return getSuccessResult(vo);
	}

	@ApiOperation(value = "修改数据库信息表",notes = "修改数据库信息表",httpMethod = "POST")
	@RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity update(@ModelAttribute@Valid DbInfoUpdateForm form) throws Exception {
		DbInfoPo po = CopyUtil.transfer(form, DbInfoPo.class);
		if (StringUtils.isNotBlank(form.getDbPassword())){
			String aesdec =AesEncryptPaddingUtil.decrypt(form.getDbPassword(),aeskey);
			if (StringUtils.isBlank(aesdec)){
				getFailResult("密码加密方式有误");
			}
			po.setDbPassword(AesEncryptPaddingUtil.encrypt(aesdec,aeskey));
		}
		dbInfoService.update(po);
		return getSuccessResult();
	}

	@ApiOperation(value = "删除数据库信息表",notes = "删除数据库信息表",httpMethod = "POST")
	@RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity delete(@ApiParam(value = "dbIds", required = true)@RequestParam String dbIds) throws BusinessServiceException {
		logger.info("删除数据库信息");
		if (StringUtils.isNotBlank(dbIds)){
			dbInfoService.batchDelete(dbIds);
		}
		return getSuccessResult();
	}


	@ApiOperation(value = "查询数据库信息表名称列表",notes = "查询数据库信息表名称列表",httpMethod = "GET")
	@RequestMapping(value = "/queryDbNameList", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<CentreListResponse<DbInfoDbNameListVo>> queryDbNameList(@ModelAttribute@Valid DbInfoQueryForm form) throws BusinessServiceException {
		DbInfoCondition condition = this.getConditionByQueryForm(form);
		condition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
		List<DbInfoPo> poList = dbInfoService.queryList(condition);
		List<DbInfoDbNameListVo> voList = CopyUtil.transfer(poList, DbInfoDbNameListVo.class);
		return getSuccessResult(getListResponse(voList));
	}

	@ApiOperation(value = "数据库连通性侧",notes = "数据库连通性侧",httpMethod = "GET")
	@RequestMapping(value = "/testConnection", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<String> scan(@ApiParam(value = "id", required = true)@RequestParam(value = "dbId") Integer dbId) throws BusinessServiceException {
		Boolean flag=true;
		String msg="连接成功";
		Map<Boolean ,String> maps = dbInfoService.testConnections(dbId);

		for (Map.Entry<Boolean ,String> entry : maps.entrySet()) {
			flag=entry.getKey();
			msg=entry.getValue();
			System.out.println("key:" + entry.getKey() + ";value:" + entry.getValue());
		}

		if(flag){
			return getSuccessResult(msg);
		}else {
			return getFailResult(msg);
		}



	}

	/**
	 * DbInfoQueryForm转换为DbInfoCondition
	 *
	 * @param form
	 * @return
	 */
	private DbInfoCondition getConditionByQueryForm(DbInfoQueryForm form) {
		DbInfoCondition condition = CopyUtil.transfer(form, DbInfoCondition.class);
		return condition;
	}

}